package bjut.zrpc.core.optimization.utils;



import bjut.zrpc.core.optimization.enums.ZRpcConfigEnum;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Author: zhuzhiming
 * @Date: 2022/6/23 21:48
 */
public final class PropertiesReadUtil {


    private static final ConcurrentHashMap<String, Properties> PROPERTIES_MAP = new ConcurrentHashMap<>();

    public static Properties readProperties(String fileName) {
        Properties properties;

        properties = PROPERTIES_MAP.get(fileName);

        if (properties != null) {
            return properties;
        }

        URL resource = Thread.currentThread().getContextClassLoader().getResource("");

        String filePath = "";

        if (resource != null) {
            filePath = resource.getPath() + fileName;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {
            properties = new Properties();
            properties.load(reader);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        PROPERTIES_MAP.put(fileName, properties);
        return properties;
    }

    public static String getConfig(String configName) {

        String[] propertiesArr = ZRpcConfigEnum.ZRPC_CONFIG_NAME.getPropertyValue();
        String configValue = "true";
        for (String config : propertiesArr) {
            Properties properties = PropertiesReadUtil.readProperties(config);
            if (properties != null) {
                configValue = properties.getProperty(configName);
                if (configValue != null && !configValue.equals("true")) {
                    break;
                }
            }
        }

        return configValue == null ? "true" : configValue;

    }

}
